import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User:
 * Date: 2025-03-09
 * Time: 22:35
 */
class Solution{
    public List<List<Integer>> fourSum(int[] nums, int target){
        List<List<Integer>> ret = new ArrayList<>();
        Arrays.sort(nums);
        int n = nums.length;
        for (int i = 0; i < n; ) {
            for (int j = i+1; j < n; ) {
                int left = j+1, right = n-1;
                int aim = target - nums[i] -nums[j];
                while(left < right){
                    int sum = nums[left] + nums[right];
                    if(sum > aim) right--;
                    else if(sum < aim) left++;
                    else{
                        ret.add(Arrays.asList(nums[i], nums[j], nums[right--], nums[left++]));
                        while(left < right && nums[left] == nums[left-1]) left++;
                        while(left < right && nums[right] == nums[right+1]) right--;
                    }
                }
                j++;
                while(j < n && nums[j] == nums[j-1]) j++;
            }
            i++;
            while(i < n && nums[i] == nums[i-1]) i++;
        }
        return ret;
    }
}

public class demo2 {
    public static void main(String[] args) {
        Solution solution = new Solution();
        int[] n = {1,0,-1,0,-2,2};
        List<List<Integer>> ret = solution.fourSum(n,0);
        System.out.println(ret);
    }
}
